package com.mybed.crm.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybed.crm.mapper.*;
import com.mybed.crm.pojo.dto.PageDeptDto;
import com.mybed.crm.pojo.dto.PageReportChannelDto;
import com.mybed.crm.pojo.dto.PageReportCluesDto;
import com.mybed.crm.pojo.dto.PageReportContractDto;
import com.mybed.crm.pojo.pojo.Activity;
import com.mybed.crm.pojo.pojo.Contract;
import com.mybed.crm.pojo.vo.*;
import com.mybed.crm.result.PageResult;
import com.mybed.crm.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;

import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private DictDetailMapper dictDataMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private CluesMapper cluesMapper;

    private PageResult pageResult = new PageResult();


    /**
     * `漏斗图统计`
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVo getBaseInfo(String beginCreateTime, String endCreateTime) {
        IndexBaseInfoVo result = new IndexBaseInfoVo();
        //获取用户名
        String userName = null;
        try {
            result.setBusinessNum(reportMapper.getBusinessNum(beginCreateTime, endCreateTime));
            result.setCluesNum(reportMapper.getCluesNum(beginCreateTime, endCreateTime));
            result.setContractNum(reportMapper.getContractNum(beginCreateTime, endCreateTime));
            result.setSalesAmount(reportMapper.getSalesAmount(beginCreateTime, endCreateTime));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }

    //客户统计
    @Override
    public LineChartVo contractStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVo lineChartVo = new LineChartVo();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setXAxis(timeList);
            List<LineSeriesVo> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.contractStatistics(beginCreateTime, endCreateTime);
            LineSeriesVo lineSeriesDTO1 = new LineSeriesVo();
            lineSeriesDTO1.setName("新增客户数");
            LineSeriesVo lineSeriesDTO2 = new LineSeriesVo();
            lineSeriesDTO2.setName("客户总数");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                } else {
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
           e.printStackTrace();
        }
            return lineChartVo;
    }

    /**
     * 客户统计的分页查询
     * @return
     */
    @Override
    public PageResult queryPageContract(PageReportContractDto pageReportContractDto) {
        IPage<Contract> page = new Page<>(pageReportContractDto.getPageNum(),pageReportContractDto.getPageSize());
        IPage<Contract> iPage = contractMapper.queryPageContract(page,null,pageReportContractDto);
        pageResult.insertData(iPage);
        return pageResult;
    }

    /**
     * 商机转化龙虎榜
     */
    @Override
    public List<Map<String, Object>> businessChangeStatisticsForIndex(IndexStatisticsVo request) {
        int allBusiness = businessMapper.countAllBusiness(request.getBeginCreateTime(),request.getEndCreateTime());
        List<Map<String,Object>> list= businessMapper.countAllContractByUser(request);
        for (Map<String, Object> datum : list) {
            Long num= (Long) datum.get("num");
            log.info("allBusiness:"+allBusiness);
            log.info("num:"+num);
            datum.put("radio",getRadio(allBusiness,num));
        }
        return list;
    }

    //线索转化龙虎榜
    @Override
    public List<Map<String, Object>> salesChangeStatisticsForIndex(IndexStatisticsVo request) {
        /*Integer countAllClues = cluesMapper.countAllClues(request.getBeginCreateTime(), request.getEndCreateTime());*/
        List<Map<String, Object>> list = cluesMapper.countAllCluesSale(request);
        for (Map<String, Object> map : list) {

            if(map.get("radio")==null){
                map.put("radio",0);
            }
        }
        System.out.println(list);
        return list;
    }


    /**
     * 线索统计的分页查询
/**
     * 销售统计的分页查询
     * @param beginCreateTime
     * @param endCreateTime
     * @param pageDeptDto
     * @return
     */
    @Override
    public PageResult queryPageDept(LocalDate beginCreateTime, LocalDate endCreateTime, PageDeptDto pageDeptDto) {
        pageDeptDto.setBeginCreateTime(beginCreateTime);
        pageDeptDto.setEndCreateTime(endCreateTime);
        IPage<PageDeptVo> page = new Page<>(pageDeptDto.getPageNum(),pageDeptDto.getPageSize());
        IPage<PageDeptVo> iPage = contractMapper.queryPageDept(page,null,pageDeptDto);
        pageResult.insertData(iPage);
        return pageResult;


    }
    /**
     * 线索统计的分页查询
     */
    @Override
    public PageResult queryPageClue(PageReportCluesDto pageReportCluesDto) {
        IPage<PageCluesVo> page = new Page<>(pageReportCluesDto.getPageNum(),pageReportCluesDto.getPageSize());
        IPage<PageCluesVo> iPage = contractMapper.queryPageClue(page,null,pageReportCluesDto);
        pageResult.insertData(iPage);
        return pageResult;
    }

    /**
     * 渠道统计的分页查询
     * @param pageReportChannelDto
     * @return
     */
    @Override
    public PageResult queryPageActivity(PageReportChannelDto pageReportChannelDto) {
        IPage<PageReportChannelVo> page = new Page<>(pageReportChannelDto.getPageNum(),pageReportChannelDto.getPageSize());
        IPage<PageReportChannelVo> iPage = contractMapper.queryPageActivity(page,null,pageReportChannelDto);
        pageResult.insertData(iPage);
        return pageResult;
    }

    /**线索统计查询
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public LineChartVo cluesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVo lineChartVo = new LineChartVo();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setXAxis(timeList);
            List<LineSeriesVo> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.cluesStatistics(beginCreateTime, endCreateTime);
            log.info("拿到的集合map为：{}",statistics);
            LineSeriesVo lineSeriesDTO1 = new LineSeriesVo();
            lineSeriesDTO1.setName("新增线索数");
            LineSeriesVo lineSeriesDTO2 = new LineSeriesVo();
            lineSeriesDTO2.setName("线索总数");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                } else {
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lineChartVo;
    }

    //销售统计
    @Override
    public LineChartVo salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVo lineChartVo =new LineChartVo();
        try {
            List<String> timeList= findDates(beginCreateTime,endCreateTime);
            lineChartVo.setXAxis(timeList);
            List<LineSeriesVo> series = new ArrayList<>();
            List<Map<String,Object>>  statistics = contractMapper.salesStatistics(beginCreateTime,endCreateTime);
            LineSeriesVo lineSeriesVo=new LineSeriesVo();
            lineSeriesVo.setName("销售统计");
            int sum=0;
            for (String s : timeList) {
                Optional optional=  statistics.stream().filter(d->d.get("dd").equals(s)).findFirst();
                if(optional.isPresent()){
                    Map<String,Object> cuurentData=  (Map<String,Object>)optional.get();
                    lineSeriesVo.getData().add(cuurentData.get("sales"));
                }else{
                    lineSeriesVo.getData().add(0);
                }
            }
            series.add(lineSeriesVo);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
             e.printStackTrace();
        }
        return  lineChartVo;
    }

    //渠道统计 饼图一
    @Override
    public Object chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.chanelStatistics(beginCreateTime,endCreateTime);
        log.info("拿到的data内有没有数据呢？是什么呢？{}",data);
        for (Map<String, Object> datum : data) {
            String subjectValue= (String) datum.get("channel");

            String lable= dictDataMapper.selectDictLabel("clues_item",subjectValue);

            datum.put("channel",lable);
        }
        return data;
    }

    //活动统计 饼图2
    @Override
    public Object activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.activityStatistics(beginCreateTime,endCreateTime);

        for (Map<String, Object> datum : data) {
            Long activityId= (Long) datum.get("activity_id");
            Activity activity = activityMapper.selectActivityById(activityId);
            if(activity == null){
                datum.put("activity", "其他");
            }else{
                datum.put("activity", activity.getName());
            }
            datum.remove("activity_id");
        }
        return data;
    }

    //漏斗统计
    @Override
    public VulnerabilityMapVo getVulnerabilityMap(String beginCreateTime, String endCreateTime) {
        VulnerabilityMapVo result = new VulnerabilityMapVo();
        try {
            result.setEffectiveCluesNums(reportMapper.getCluesNum(beginCreateTime, endCreateTime));
            Integer invalidCluesNums =reportMapper.getInvalidCluesNums();
            result.setCluesNums(reportMapper.getCluesNum(beginCreateTime, endCreateTime)+invalidCluesNums);
            result.setBusinessNums(reportMapper.getBusinessNum(beginCreateTime, endCreateTime));
            result.setContractNums(reportMapper.getContractNum(beginCreateTime, endCreateTime));
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public IndexVo getIndexInfo(String beginCreateTime, String endCreateTime) {
        LocalDate now = LocalDate.now();
        LocalDate end = now.plusDays(1);
        IndexVo result = new IndexVo();
        Integer invalidCluesNums =reportMapper.getInvalidCluesNums();
        result.setCluesNum(reportMapper.getCluesNum(beginCreateTime, endCreateTime)+invalidCluesNums);
        result.setBusinessNum(reportMapper.getBusinessNum(beginCreateTime, endCreateTime));
        result.setContractNum(reportMapper.getContractNum(beginCreateTime, endCreateTime));
        result.setSalesAmount(reportMapper.getSalesAmount(beginCreateTime, endCreateTime));
        result.setTodayCluesNum( reportMapper.getTodayCluesNum(now, end));
        result.setTodayBusinessNum( reportMapper.getTodayBusinessNum(now, end));
        result.setTodayContractNum( reportMapper.getTodayContractNum(now, end));
        result.setTodaySalesAmount( reportMapper.getTodaySalesAmount(now,end));
        //reportMapper.getToallocatedCluesNum(beginCreateTime, endCreateTime)
        result.setToallocatedCluesNum(reportMapper.getToallocatedCluesNum(beginCreateTime, endCreateTime));
        result.setTofollowedCluesNum(reportMapper.getTofollowedCluesNum(beginCreateTime, endCreateTime));
        //reportMapper.getToallocatedBusinessNum(beginCreateTime, endCreateTime)
        result.setToallocatedBusinessNum(4);
        //reportMapper.getTofollowedBusinessNum(beginCreateTime, endCreateTime)
        result.setTofollowedBusinessNum(reportMapper.getTofollowedBusinessNum(beginCreateTime, endCreateTime));
        return result;
    }


    /**
     * 查询两个日期之间的所有日期
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }

    /**
     * 计算百分比
     */
    private BigDecimal getRadio(Integer all, Long num) {
        if(all.intValue()==0){
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal,4,BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }
}
